package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.interceptor.LoginInterceptor;

import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.bean.ResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public  class CartController {
    @Autowired
    CartService cartService;

    //feign调用的方法，feign是没有cookie的，所以要通过传参的方式传userId
    @GetMapping("user/{userId}")
    @ResponseBody
    public  ResponseVo<List<Cart>>  queryCheckedCarts(@PathVariable("userId") Long userId){
        List<Cart> carts=  cartService.queryCheckedCarts(userId);
        return ResponseVo.ok(carts);
    }

    //请求参数：?skuId=40&count=2
    //新增购物车
    @GetMapping
    public String saveCart(Cart cart) {
        cartService.saveCart(cart);
        return "redirect:http://cart.gmall.com/addCart.html?skuId=" + cart.getSkuId() + "&count=" + cart.getCount();
    }

    //重定向到这个路径，查询购物车展示到页面中（回显购物车）
    //请求参数：skuId,count
    @GetMapping("addCart.html")
    public String queryCartBySkuId(@RequestParam("skuId") Long skuId, @RequestParam("count") Integer count,
                                   Model model) {
        Cart cart = cartService.queryCartBySkuId(skuId, count);
        model.addAttribute("cart", cart);
        return "addCart";
    }

    //查询购物车，未登录的与登录的购物车合并
    @GetMapping("cart.html")
    public String queryCarts(Model model) {
      List<Cart> carts =  cartService.queryCarts();
      model.addAttribute("carts",carts);
      return "cart";
    }

    //更改购物车里一条sku的count
    //{skuId,count}
    @PostMapping("updateNum")
    @ResponseBody
    public ResponseVo  updateNum(@RequestBody Cart cart){
        cartService.updateNum(cart);
        return ResponseVo.ok();
    }

    /**
     * 删除购物车里一条sku
     * @param skuId
     * @return
     */
    @PostMapping("deleteCart")
    @ResponseBody
    public ResponseVo  deleteCart(@RequestParam("skuId") Long skuId){
        cartService.deleteCart(skuId);
        return ResponseVo.ok();
    }




    @GetMapping("test")
    @ResponseBody
    public String test() {
        System.out.println(LoginInterceptor.getUserInfo());
        return "hello";
    }

}
